/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.jr2tecnologia.model;

import br.com.jr2tecnologia.model.entity.KeyResponse;
import br.com.jr2tecnologia.model.persistence.DAOFactory;
import br.com.jr2tecnologia.model.repository.KeyResponseRepository;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author ronildo
 */

@Stateless
public class KeyResponsePersistence implements KeyResponsePersistenceLocal{

    @PersistenceContext
    private EntityManager em;
    private KeyResponseRepository keyResponseRepository;

    @PostConstruct
    public void initialize(){
        keyResponseRepository = DAOFactory.getKeyResponseRepository(em);
    }

    public boolean persist(KeyResponse keyResponse){
        keyResponse.setPkKeyResponse(null);
        keyResponse.setDefaultKey(false);
        
        if(keyResponseRepository.findByName(keyResponse.getName()) == null){
            keyResponseRepository.persist(keyResponse);
            return true;
        } else
            return false;

    }

    public void update(KeyResponse keyResponse){
        keyResponseRepository.update(keyResponse);
    }

    public void remove(KeyResponse keyResponse){
        keyResponseRepository.remove(keyResponse, keyResponse.getPkKeyResponse());
    }

    public KeyResponse findById(KeyResponse keyResponse){
        return keyResponseRepository.findById(keyResponse.getPkKeyResponse());
    }

    public KeyResponse findByName(String name){
        return keyResponseRepository.findByName(name);
    }


    public KeyResponse findByNameWithoutCasesensitive(String name){
        return keyResponseRepository.findByNameWithoutCasesensitive(name);
    }

    public List<KeyResponse> list(KeyResponse keyResponse){
        return keyResponseRepository.list(keyResponse);
    }

    public List<KeyResponse> listAll(){
        return keyResponseRepository.listAll();
    }

    public void makeDefaultKeyResponse(KeyResponse oldDefaultKeyResponse, KeyResponse newDefaultKeyResponse){
        if(oldDefaultKeyResponse != null){
            oldDefaultKeyResponse.setDefaultKey(false);
            keyResponseRepository.update(oldDefaultKeyResponse);
        }
        newDefaultKeyResponse.setDefaultKey(true);
        keyResponseRepository.update(newDefaultKeyResponse);
    }
}
